package weaver.tools.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.cube.biz.ParamUtil;
import com.engine.cube.cmd.app.SaveModeInfo;
import com.engine.cube.cmd.app.SaveModeRightList;
import com.engine.cube.cmd.app.SaveQuickSearchInfoCmd;
import com.engine.cube.cmd.form.AddFormCmd;
import com.engine.cube.cmd.form.AddVirtualFormCmd;
import com.engine.cube.cmd.form.RefreshformCmd;
import com.engine.cube.cmd.list.ListInfoSave;
import com.engine.cube.cmd.list.SaveFormfieldsCmd;
import com.engine.cube.cmd.list.SaveRightinfoCmd;
import com.engine.workflow.biz.FormFieldSetBiz;
import com.engine.workflow.cmd.formManage.fieldManage.SaveFieldCmd;
import com.weaver.formmodel.util.DateHelper;
import weaver.conn.RecordSet;
import weaver.formmode.exceldesign.ExcelsetInitManager;
import weaver.formmode.service.CommonConstant;
import weaver.formmode.setup.ModeLayoutUtil;
import weaver.general.BaseBean;
import weaver.general.LabelUtil;
import weaver.general.SecurityHelper;
import weaver.general.Util;
import weaver.hrm.User;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class QuickCreateCmd extends AbstractCommonCommand<Map<String, Object>> {
    private int type;

    public QuickCreateCmd(Map<String, Object> params, User user, int type) {
        this.user = user;
        this.params = params;
        this.type = type;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public List<BizLogContext> getLogContexts() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> resultMap = new HashMap<>();
        //String viewTableInfoStr = Util.null2String(params.get("viewTableInfo"));
        String modeName = Util.null2String(params.get("modeName"));
        String searchName = Util.null2String(params.get("searchName"));
        String formType = Util.null2String(params.get("formType"));
        String byMainTableName = Util.null2String(params.get("byMainTableName"));
        String layoutRownum = Util.null2String(params.get("layoutRownum"));
        String layoutStyle = Util.null2String(params.get("layoutStyle"));
        String mainFieldname = Util.null2String(params.get("mainFieldname"));
        String detailFieldname = Util.null2String(params.get("detailFieldname"));
        String datasourceid = Util.null2String(params.get("datasourceid"));
        String viewtablename = Util.null2String(params.get("viewtablename"));
        JSONObject json = new JSONObject();
        json.put("modeName", modeName);
        json.put("searchName", searchName);
        json.put("formType", formType);
        json.put("byMainTableName", byMainTableName);
        json.put("layoutRownum", layoutRownum);
        json.put("layoutStyle", layoutStyle);
        json.put("mainFieldname", mainFieldname);
        json.put("detailFieldname", detailFieldname);
        json.put("datasourceid", datasourceid);
        json.put("viewtablename", viewtablename);
        String fieldListStr = Util.null2String(ParamUtil.get(params, "fieldList"));
        String appid = getAppid();
        if ("".equals(appid)) {
            resultMap.put("status", "-1");
            resultMap.put("errorMsg", "找不到“历史数据迁移”应用，请先创建，创建的数据都放到这里");
            return resultMap;
        }


        JSONObject viewTableInfo = json;
        JSONArray fieldList = JSONArray.parseArray(fieldListStr);
        resultMap = structureModeInfo(appid, viewTableInfo, fieldList);
        resultMap.put("status", "1");
        return resultMap;
    }

    public Map<String, Object> structureDetailModeInfo(String appid, JSONObject viewTableInfo, JSONArray fieldList) {
        Map<String, Object> resultMap = new HashMap<>();

        String newFieldNames = "";
        String oldFieldNames = "";
        String tableName = "";

        String modename = Util.null2String(viewTableInfo.getString("modeName"));
        String searchName = Util.null2String(viewTableInfo.getString("searchName"));
        String formType = Util.null2String(viewTableInfo.getString("formType"));
        String byMainTableName = Util.null2String(viewTableInfo.getString("byMainTableName"));
        String layoutRownum = Util.null2String(viewTableInfo.getString("layoutRownum"));
        String layoutStyle = Util.null2String(viewTableInfo.getString("layoutStyle"));
        String mainFieldname = Util.null2String(viewTableInfo.getString("mainFieldname"));
        String detailFieldname = Util.null2String(viewTableInfo.getString("detailFieldname"));
        String datasourceid = Util.null2String(viewTableInfo.getString("datasourceid"));
        String viewtablename = Util.null2String(viewTableInfo.getString("viewtablename"));
        int formId = Util.getIntValue(byMainTableName);
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from workflow_bill where id=?", formId);
        String mainTableName = "";
        if (rs.next()) {
            mainTableName = Util.null2String(rs.getString("tablename"));
        }
        rs.executeQuery("select max(orderid) from Workflow_billdetailtable where billid= ? ", formId);
        int maxOrderId = 0;
        if (rs.next()) {
            maxOrderId = Util.getIntValue(rs.getString(1), 0);
        }
        FormFieldSetBiz formFieldSetBiz = new FormFieldSetBiz(formId, 1, user);
        formFieldSetBiz.setDetailTableOrderId(maxOrderId);
        String detailTableName = mainTableName + "_dt" + (maxOrderId + 1);
        try {
            formFieldSetBiz.createDetailTable(detailTableName);
            formFieldSetBiz.submitOperate();
            tableName = detailTableName;
        } catch (Exception e) {
            this.writeLog(e);
        }


        //往明细表中新增字段和插入数据未完成，主表新增字段改造也未完成。
        for (int i = 0; i < fieldList.size(); i++) {
            JSONObject fieldObject = fieldList.getJSONObject(i);
            int fieldTypeOption = Util.getIntValue(fieldObject.getString("fieldTypeOption"), 0);
            String fieldattr = Util.null2String(fieldObject.getString("fieldattr"));
            String fieldType = "";
            fieldType = getFiledType(fieldTypeOption, fieldattr);

            String isnewfield = Util.null2String(fieldObject.getString("isnewfield"));
            String fieldname = Util.null2String(fieldObject.getString("fieldname"));
            String ccname = ",id,requestid,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,uuid,";

            if ("1".equals(isnewfield)) {
                oldFieldNames += fieldname + ",";
                if (ccname.indexOf("," + fieldname.toLowerCase() + ",") > -1) {
                    fieldname = fieldname + "_cp";
                }
                newFieldNames += fieldname + ",";
                Map<String, Object> sfc_params = new HashMap<>();
                sfc_params.put("description", fieldObject.getString("fieldlabelname"));
                sfc_params.put("fieldName", fieldname);
                sfc_params.put("ownerTable", detailTableName);
                sfc_params.put("orderNo", fieldObject.getString("showorder"));
                sfc_params.put("isFromMode", "1");
                sfc_params.put("fieldId", "");
                sfc_params.put("formId", formId);
                sfc_params.put("isBill", "1");
                sfc_params.put("tableType", "detailfield");
                //byte[] bytes = Base64.getDecoder().decode(fieldType.replace("\r\n", ""));
                //fieldType = new String(bytes,"UTF-8");
                //base64加密
                byte[] bytes = Base64.getEncoder().encode(fieldType.replace("\r\n", "").getBytes());
                try {
                    fieldType = new String(bytes, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    this.writeLog(e);
                }
                sfc_params.put("fieldType", fieldType);
                sfc_params.put("templateField", "false");
                SaveFieldCmd saveFieldCmd = new SaveFieldCmd(sfc_params, user);
                Map<String, Object> mapresult = saveFieldCmd.execute(null);
                this.writeLog(mapresult);
            }
        }
        addDataDetail(mainTableName, tableName, viewtablename, newFieldNames, oldFieldNames, mainFieldname, detailFieldname, datasourceid);

        return resultMap;
    }

    public String getFiledType(int fieldTypeOption, String fieldattr) {
        String fieldType = "";
        switch (fieldTypeOption) {
            case 0://单行文本
                fieldType = "[\"input\",\"text\",\"" + fieldattr + "\"]";
                break;
            case 1://单人力资源
                fieldType = "[\"browser\",{\"value\":\"1\",\"valueSpan\":\"人力资源\"," +
                        "\"replaceDatas\":[{\"id\":\"1\",\"itemorderid\":\"1\",\"name\":\"人力资源\"," +
                        "\"title\":\"人员-人力资源\",\"parenttitle\":\"人员\"}]}]";
                break;
            case 2://多人力资源
                fieldType = "[\"browser\",{\"value\":\"17\",\"valueSpan\":\"多人力资源\"," +
                        "\"replaceDatas\":[{\"id\":\"17\",\"itemorderid\":\"17\",\"name\":\"多人力资源\",\"title\":\"人员-多人力资源\"," +
                        "\"parenttitle\":\"人员\"}]}]";
                break;
            case 3://上传附件
                fieldType = "[\"upload\",\"file\"]";
                break;
            case 4://多行文本
                fieldType = "[\"textarea\",4]";
                break;
            case 5://部门
                fieldType = "[\"browser\",{\"value\":\"4\",\"valueSpan\":\"部门\"," +
                        "\"replaceDatas\":[{\"id\":\"4\",\"itemorderid\":\"4\",\"name\":\"部门\",\"title\":\"组织-部门\",\"parenttitle\":\"组织\"}]}]";
                break;
            case 6://分部
                fieldType = "[\"browser\",{\"value\":\"164\",\"valueSpan\":\"分部\"," +
                        "\"replaceDatas\":[{\"id\":\"164\",\"itemorderid\":\"164\",\"name\":\"分部\",\"title\":\"组织-分部\",\"parenttitle\":\"组织\"}]}]";
                break;
            case 7://多部门
                fieldType = "[\"browser\",{\"value\":\"57\",\"valueSpan\":\"多部门\"," +
                        "\"replaceDatas\":[{\"id\":\"57\",\"itemorderid\":\"57\",\"name\":\"多部门\",\"title\":\"组织-多部门\",\"parenttitle\":\"组织\"}]}]";
                break;
            case 8://多分部
                fieldType = "[\"browser\",{\"value\":\"194\",\"valueSpan\":\"多分部\"," +
                        "\"replaceDatas\":[{\"id\":\"194\",\"itemorderid\":\"194\",\"name\":\"多分部\",\"title\":\"组织-多分部\",\"parenttitle\":\"组织\"}]}]";
                break;
            case 9://整数
                fieldType = "[\"input\",\"int\"]";
                break;
            case 10://浮点数
                fieldType = "[\"input\",\"float\",\"" + fieldattr + "\"]";
                break;
            default:
                fieldType = "[\"input\",\"text\",\"256\"]";
                break;
        }
        return fieldType;
    }

    public void addDataDetail(String mainTableName, String tableName, String oldTableName, String newFieldNames, String oldFieldNames, String mainFieldname, String detailFieldname, String datasourceid) {
        if (newFieldNames.length() == 0) {
            return;
        }
        RecordSet rs = new RecordSet();
        String sql = "select * from datasourcesetting where id=? ";
        rs.executeQuery(sql, datasourceid);
        String poolname = "";
        String username = "";
        if (rs.next()) {
            String id = Util.null2String(rs.getString("id"));
            //poolname = Util.null2String(rs.getString("pointid"));
            username = Util.null2String(rs.getString("username"));
            String encodeStr = "/c4Q2hAVXFc=";
            username = username.indexOf(encodeStr) > -1 ? SecurityHelper.decrypt(SecurityHelper.KEY, username) : username;
        }

        if (newFieldNames.length() > 0 && newFieldNames.endsWith(",")) {
            newFieldNames = newFieldNames.substring(0, newFieldNames.length() - 1);
        }
        if (oldFieldNames.length() > 0 && oldFieldNames.endsWith(",")) {
            oldFieldNames = oldFieldNames.substring(0, oldFieldNames.length() - 1);
        }
        String insertSql = "insert into " + tableName + " (" + newFieldNames + ") " +
                "select " + oldFieldNames + " FROM " + username + "." + oldTableName;
        this.writeLog("明细表数据迁移sql：");
        rs.executeUpdate(insertSql);

        //update testb b set object_name=(select a.object_name from testa a where
        //a.object_id=b.object_id)
        //where exists (select 1 from testa a where a.object_id=b.object_id);
        //————————————————
        //版权声明：本文为CSDN博主「Hehuyi_In」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
        //原文链接：https://blog.csdn.net/Hehuyi_In/article/details/124222769

        boolean isMySQL = (rs.getDBType()).toLowerCase().equals("mysql");
        String dbType = CommonConstant.DB_TYPE;
        boolean isOracle = dbType.equals("oracle");
        boolean isSqlServer = dbType.equals("sqlserver");
        boolean isDB2 = (rs.getDBType()).toLowerCase().equals("db2");
        if (!isSqlServer) {
            sql = "update " + tableName + " b set mainid=(select id from " + mainTableName + " a where a." + mainFieldname + "=b." + detailFieldname + " and rownum =1 ) " +
                    "where exists (select 1 from " + mainTableName + " a where a." + mainFieldname + "=b." + detailFieldname + ")";
        } else {
            //UPDATE a SET WtNo=b.NO
            //from WT_Task a
            //INNER JOIN WT_BasicInformation b ON a.WtId=b.ID;

            sql = "UPDATE a SET mainid =b.id " +
                    "from " + tableName + " a " +
                    "INNER JOIN " + mainTableName + " b ON a." + detailFieldname + "=b." + mainFieldname;
        }
        this.writeLog("明细表迁移sql:" + sql);
        rs.executeUpdate(sql);

    }

    public Map<String, Object> structureModeInfo(String appid, JSONObject viewTableInfo, JSONArray fieldList) {

        RecordSet rs = new RecordSet();
        Map<String, Object> resultMap = new HashMap<>();
        String modename = Util.null2String(viewTableInfo.getString("modeName"));
        String formType = Util.null2String(viewTableInfo.getString("formType"));
        String datasourceid = Util.null2String(viewTableInfo.getString("datasourceid"));
        String viewtablename = Util.null2String(viewTableInfo.getString("viewtablename"));
        if (formType.equalsIgnoreCase("1")) {//明细表
            this.structureDetailModeInfo(appid, viewTableInfo, fieldList);
            return resultMap;
        }
        Map<String, Object> addForm_params = new HashMap<>();

        String labelname = modename;
        String newTableName = viewtablename;

        String modetype = appid;
        labelname = getNewVirFormName(labelname);
        addForm_params.put("labelname", labelname);
        addForm_params.put("tablename", newTableName);
        addForm_params.put("modetype", modetype);
        addForm_params.put("appid", modetype);
        AddFormCmd addFormCmd = new AddFormCmd(addForm_params, user);
        resultMap = addFormCmd.execute(null);
        String newFormid = Util.null2String(resultMap.get("formid"));
        String newFieldNames = "";
        String oldFieldNames = "";
        JSONArray newfeildArray = new JSONArray();
        String ccname = ",id,requestid,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,uuid,";
        for (int i = 0; i < fieldList.size(); i++) {
            JSONObject feildeldjson = fieldList.getJSONObject(i);
            String isshow = Util.null2String(feildeldjson.getString("isshow"));
            String fieldid = Util.null2String(feildeldjson.getString("fieldid"));
            String fieldname = Util.null2String(feildeldjson.getString("fieldname"));
            String fieldlabelname = Util.null2String(feildeldjson.getString("fieldlabelname"));
            String fieldtypeoption = Util.null2String(feildeldjson.getString("fieldtypeoption"));
            String isnewfield = Util.null2String(feildeldjson.getString("isnewfield"));
            String iscoustomtitle = Util.null2String(feildeldjson.getString("iscoustomtitle"));
            String fieldattr = Util.null2String(feildeldjson.getString("fieldattr"));
            String islink = Util.null2String(feildeldjson.getString("islink"));
            String isquery = Util.null2String(feildeldjson.getString("isquery"));
            String showorder = Util.null2String(feildeldjson.getString("showorder"));
            String fieldType = fieldtypeoption;
            fieldType = getFiledType(Util.getIntValue(fieldtypeoption, 0), fieldattr);
            if ("1".equals(isnewfield)) {
                oldFieldNames += fieldname + ",";
                if (ccname.indexOf("," + fieldname.toLowerCase() + ",") > -1) {
                    fieldname = fieldname + "_cp";
                }
                newFieldNames += fieldname + ",";
                Map<String, Object> sfc_params = new HashMap<>();
                sfc_params.put("description", fieldlabelname);
                sfc_params.put("fieldName", fieldname);
                sfc_params.put("ownerTable", newTableName);
                sfc_params.put("orderNo", showorder);
                sfc_params.put("isFromMode", "1");
                sfc_params.put("fieldId", "");
                sfc_params.put("formId", newFormid);
                sfc_params.put("isBill", "1");
                sfc_params.put("tableType", "mainfield");
                //byte[] bytes = Base64.getDecoder().decode(fieldType.replace("\r\n", ""));
                //fieldType = new String(bytes,"UTF-8");
                //base64加密
                byte[] bytes = Base64.getEncoder().encode(fieldType.replace("\r\n", "").getBytes());
                try {
                    fieldType = new String(bytes, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    this.writeLog(e);
                }
                sfc_params.put("fieldType", fieldType);
                sfc_params.put("templateField", "false");
                SaveFieldCmd saveFieldCmd = new SaveFieldCmd(sfc_params, user);
                Map<String, Object> fieldMap = saveFieldCmd.execute(null);
                String newFieldid = Util.null2String(fieldMap.get("fieldId"));
                feildeldjson.put("newfieldid", newFieldid);
                newfeildArray.add(feildeldjson);
            }
        }//字段添加结束
        viewTableInfo.put("newFormid", newFormid);
        viewTableInfo.put("newFormName", newTableName);
        Map<String, Object> sqsi_params = createModeInfo(appid, viewTableInfo, newfeildArray, false);
        Map<String, Object> resultInfo = (Map<String, Object>) sqsi_params.get("resultInfo");
        String modeid = Util.null2String(resultInfo.get("modeid"));
        String customid = Util.null2String(resultInfo.get("customid"));
        //迁移数据
       // addData(modeid, newTableName, oldRealFromName, newFieldNames, oldFieldNames, datasourceid);
        resultMap.putAll(sqsi_params);
        return resultMap;
    }

    public void addData(String modeid, String tableName, String oldTableName, String newFieldNames, String oldFieldNames, String datasourceid) {
        if (newFieldNames.length() == 0) {
            return;
        }
        RecordSet rs = new RecordSet();
        String sql = "select * from datasourcesetting where id=? ";
        rs.executeQuery(sql, datasourceid);
        String poolname = "";
        String username = "";
        if (rs.next()) {
            String id = Util.null2String(rs.getString("id"));
            //poolname = Util.null2String(rs.getString("pointid"));
            username = Util.null2String(rs.getString("username"));
            String encodeStr = "/c4Q2hAVXFc=";
            username = username.indexOf(encodeStr) > -1 ? SecurityHelper.decrypt(SecurityHelper.KEY, username) : username;
        }

        if (newFieldNames.length() > 0 && newFieldNames.endsWith(",")) {
            newFieldNames = newFieldNames.substring(0, newFieldNames.length() - 1);
        }
        if (oldFieldNames.length() > 0 && oldFieldNames.endsWith(",")) {
            oldFieldNames = oldFieldNames.substring(0, oldFieldNames.length() - 1);
        }
        String insertSql = "insert into " + tableName + " (" + newFieldNames + ") " +
                "select " + oldFieldNames + " FROM " + username + "." + oldTableName;
        this.writeLog("主表迁移数据sql:" + insertSql);
        rs.executeUpdate(insertSql);
        String updateSql = "update " + tableName + " set formmodeid=?,modedatacreater=?,modedatacreatertype=?," +
                "modedatacreatedate=?,modedatacreatetime=? ";
        rs.executeUpdate(updateSql, modeid, user.getUID(), 0, DateHelper.getCurrentDate(), DateHelper.getCurrentTime());


        Map<String, Object> moderight_params = new HashMap<>();
        moderight_params.put("rebulidFlag", "3");
        moderight_params.put("operation", "resetAllRight");
        moderight_params.put("showProgress", "1");
        moderight_params.put("modeid", modeid);
        moderight_params.put("righttype", "3");
        HttpSession session = (HttpSession) this.params.get("session");
        moderight_params.put("session", session);

        SaveModeRightList saveModeRightList = new SaveModeRightList(moderight_params, user);
        saveModeRightList.execute(null);
    }

    public Map<String, Object> createModeInfo(String appid, JSONObject viewTableInfo, JSONArray fieldList, boolean isCreateTable) {
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        boolean isMySQL = (rs.getDBType()).toLowerCase().equals("mysql");
        String dbType = CommonConstant.DB_TYPE;
        boolean isOracle = dbType.equals("oracle");
        boolean isSqlServer = dbType.equals("sqlserver");
        boolean isDB2 = (rs.getDBType()).toLowerCase().equals("db2");
        String modename = Util.null2String(viewTableInfo.getString("modeName"));
        String searchName = Util.null2String(viewTableInfo.getString("searchName"));
        String formType = Util.null2String(viewTableInfo.getString("formType"));
        String byMainTableName = Util.null2String(viewTableInfo.getString("byMainTableName"));
        String layoutRownum = Util.null2String(viewTableInfo.getString("layoutRownum"));
        String layoutStyle = Util.null2String(viewTableInfo.getString("layoutStyle"));
        String mainFieldname = Util.null2String(viewTableInfo.getString("mainFieldname"));
        String detailFieldname = Util.null2String(viewTableInfo.getString("detailFieldname"));
        String datasourceid = Util.null2String(viewTableInfo.getString("datasourceid"));
        String viewtablename = Util.null2String(viewTableInfo.getString("viewtablename"));
        String newFormid = Util.null2String(viewTableInfo.getString("newFormid"));
        String newFormName = Util.null2String(viewTableInfo.getString("newFormName"));
        int formid = 0;
        String formname = "";
        if (isCreateTable) {
            String vfieldName = "";
            String vprimarykey = "";
            String vpkgentype = "1";
            for (int i = 0; i < fieldList.size(); i++) {
                JSONObject fieldObject = fieldList.getJSONObject(i);
                String fieldname = Util.null2String(fieldObject.getString("fieldname"));
                if (i == 0) {
                    vprimarykey = fieldname;
                } else {
                    if ("id".equalsIgnoreCase(fieldname)) {
                        vprimarykey = fieldname;
                        vpkgentype = "2";
                    }
                }
                vfieldName += "," + fieldname;
            }
            if (vfieldName.length() > 0) {
                vfieldName = vfieldName.substring(1);
            }

            //创建虚拟表单
            Map<String, Object> avf_params = new HashMap<>();
            formname = getNewVirFormName(modename);
            avf_params.put("labelname", formname);
            avf_params.put("formtype", "虚拟表单");
            String sql = "select datasourcename from datasourcesetting where id=? ";
            rs.executeQuery(sql, datasourceid);
            String datasourcename = "";
            if (rs.next()) {
                String id = Util.null2String(rs.getString("id"));
                datasourcename = Util.null2String(rs.getString("datasourcename"));
            }
            avf_params.put("vdatasource", datasourcename);
            avf_params.put("schema", "");
            avf_params.put("vformtype", "1");
            avf_params.put("vtablename", viewtablename);
            avf_params.put("vprimarykey", vprimarykey);
            avf_params.put("vpkgentype", vpkgentype);
            avf_params.put("virtualformtype", "1");
            avf_params.put("appid", appid);
            avf_params.put("vfieldName", vfieldName);
            avf_params.put("modetype", appid);
            AddVirtualFormCmd addVirtualFormCmd = new AddVirtualFormCmd(avf_params, user);
            Map<String, Object> resutlMap = addVirtualFormCmd.execute(null);
            formid = Util.getIntValue(Util.null2String(resutlMap.get("formid")), 0);
            Map<String, Object> rf_params = new HashMap<>();
            rf_params.put("formId", formid);
            RefreshformCmd refreshformCmd = new RefreshformCmd(rf_params, user);
            refreshformCmd.execute(null);

            JSONArray fieldArray = new JSONArray();
            //修改字段类型
            for (int i = 0; i < fieldList.size(); i++) {
                JSONObject fieldObject = fieldList.getJSONObject(i);
                String fieldname = fieldObject.getString("fieldname");
                String fieldlabelname = fieldObject.getString("fieldlabelname");
                rs.executeQuery("select * from workflow_billfield where billid=? and fieldname=? order by dsporder", formid, fieldname);
                if (rs.next()) {
                    String fieldid = Util.null2String(rs.getString("id"));
                    fieldObject.put("fieldid", fieldid);
                    fieldArray.add(fieldObject);

                    int lableid = 0;
                    if (isSqlServer) {
                        rs1.executeSql("select indexid from HtmlLabelInfo where labelname='" + fieldlabelname + "' collate Chinese_PRC_CS_AI and languageid=7");
                    } else {
                        rs1.executeSql("select indexid from HtmlLabelInfo where labelname='" + fieldlabelname + "' and languageid=7");
                    }
                    if (rs1.next()) {
                        lableid = rs1.getInt("indexid");//如果字段名称在标签库中存在，取得标签id
                    } else {
                        lableid = new LabelUtil().getLabelIdNew(fieldlabelname);
                    }
                    rs1.executeUpdate("update workflow_billfield set fieldlabel=? where id=?", lableid, fieldid);
                }
            }
            fieldList = fieldArray;

        } else {
            formid = Util.getIntValue(newFormid);
            formname = Util.null2String(newFormName);
        }


        List<String> showFeilds = new ArrayList<>();
        List<String> showorderFeilds = new ArrayList<>();
        Map<String, String> showorderFeildsMap = new HashMap<>();
        List<String> queryFeilds = new ArrayList<>();
        List<String> linkFeilds = new ArrayList<>();

        fieldList = sortProxyAndCdn(fieldList);

        for (int i = 0; i < fieldList.size(); i++) {
            JSONObject feildeldjson = fieldList.getJSONObject(i);
            String isshow = Util.null2String(feildeldjson.getString("isshow"));
            String fieldid = Util.null2String(feildeldjson.getString("fieldid"));
            String newfieldid = Util.null2String(feildeldjson.getString("newfieldid"));
            if (newfieldid.length() == 0) {
                newfieldid = fieldid;
            }
            String islink = Util.null2String(feildeldjson.getString("islink"));
            String isquery = Util.null2String(feildeldjson.getString("isquery"));
            String showorder = Util.null2String(feildeldjson.getString("showorder"));
            if (isshow.equals("1")) {
                showFeilds.add(newfieldid);
                if (showorder.length() == 0)
                    showorder = "0";
                showorderFeilds.add(showorder);
                showorderFeildsMap.put(fieldid, showorder);
            }
            if (islink.equals("1")) {
                linkFeilds.add(newfieldid);
            }
            if (isquery.equals("1")) {
                queryFeilds.add(newfieldid);
            }
        }

        Map<String, Object> modeinfo_params = new HashMap<>();
        modeinfo_params.put("modename", modename);
        modeinfo_params.put("modetype", appid);
        modeinfo_params.put("formid", formid);
        modeinfo_params.put("modetitle", modename);
        //初始化模块
        SaveModeInfo saveModeInfo = new SaveModeInfo(modeinfo_params, user);
        Map<String, Object> resultMapMode = saveModeInfo.execute(null);
        String modeId = Util.null2String(resultMapMode.get("id"));
        if (!isCreateTable) {
            //初始化权限
            Map<String, Object> moderight_params = new HashMap<>();
            moderight_params.put("dataLength", "1");
            moderight_params.put("operation", "saveModeRight");
            moderight_params.put("higherlevel_0", "1");
            moderight_params.put("isRoleLimited_0", "0");
            moderight_params.put("importtype_0", "1");
            moderight_params.put("joblevel_0", "2");
            moderight_params.put("layoutorder_0", "-1");
            moderight_params.put("modefieldtype_0", "1");
            moderight_params.put("browsersharetype_0", "1");
            moderight_params.put("relatedid4_0", "2");
            moderight_params.put("righttype_0", "1");
            moderight_params.put("rolefieldtype_0", "1");
            moderight_params.put("rolelevel_0", "0");
            moderight_params.put("sharetype_0", "4");
            moderight_params.put("showlevel_0", "0");
            moderight_params.put("modeid", modeId);
            moderight_params.put("righttype", "3");
            SaveModeRightList saveModeRightList = new SaveModeRightList(moderight_params, user);
            saveModeRightList.execute(null);
            //人员、部门、分部权限
            for (int i = 0; i < fieldList.size(); i++) {
                JSONObject feildeldjson = fieldList.getJSONObject(i);
                String fieldid = Util.null2String(feildeldjson.getString("fieldid"));
                String newfieldid = Util.null2String(feildeldjson.getString("newfieldid"));
                String fieldtypeoption = Util.null2String(feildeldjson.getString("fieldtypeoption"));
                if (newfieldid.length() == 0) {
                    newfieldid = fieldid;
                }
                String isright = Util.null2String(feildeldjson.getString("isright"));
                if (isright.equals("1")) {
                    if ("1".equals(fieldtypeoption) || "2".equals(fieldtypeoption)) {//人员
                        Map<String, Object> moderight_params_user = new HashMap<>();
                        moderight_params_user.put("dataLength", "1");
                        moderight_params_user.put("operation", "saveModeRight");
                        moderight_params_user.put("higherlevel_0", "1");
                        moderight_params_user.put("isRoleLimited_0", "0");
                        moderight_params_user.put("importtype_0", "1");
                        moderight_params_user.put("joblevel_0", "2");
                        moderight_params_user.put("layoutorder_0", "-1");
                        moderight_params_user.put("modefieldtype_0", "1");
                        moderight_params_user.put("browsersharetype_0", "1");
                        moderight_params_user.put("relatedid1000_0", newfieldid);
                        moderight_params_user.put("righttype_0", "1");
                        moderight_params_user.put("rolefieldtype_0", "1");
                        moderight_params_user.put("rolelevel_0", "0");
                        moderight_params_user.put("sharetype_0", "1000");
                        moderight_params_user.put("showlevel_0", "0");
                        moderight_params_user.put("modeid", modeId);
                        moderight_params_user.put("righttype", "3");
                        SaveModeRightList saveModeRightList_user = new SaveModeRightList(moderight_params_user, user);
                        saveModeRightList_user.execute(null);
                    } else if ("5".equals(fieldtypeoption) || "7".equals(fieldtypeoption)) {//部门
                        Map<String, Object> moderight_params_user = new HashMap<>();
                        moderight_params_user.put("dataLength", "1");
                        moderight_params_user.put("operation", "saveModeRight");
                        moderight_params_user.put("higherlevel_0", "1");
                        moderight_params_user.put("isRoleLimited_0", "0");
                        moderight_params_user.put("importtype_0", "1");
                        moderight_params_user.put("joblevel_0", "2");
                        moderight_params_user.put("layoutorder_0", "-1");
                        moderight_params_user.put("modefieldtype_0", "2");
                        moderight_params_user.put("browsersharetype_0", "1");
                        moderight_params_user.put("relatedid1000_0", newfieldid);
                        moderight_params_user.put("righttype_0", "1");
                        moderight_params_user.put("rolefieldtype_0", "1");
                        moderight_params_user.put("rolelevel_0", "0");
                        moderight_params_user.put("sharetype_0", "1000");
                        moderight_params_user.put("showlevel_0", "0");
                        moderight_params_user.put("modeid", modeId);
                        moderight_params_user.put("righttype", "3");
                        SaveModeRightList saveModeRightList_user = new SaveModeRightList(moderight_params_user, user);
                        saveModeRightList_user.execute(null);
                    } else if ("6".equals(fieldtypeoption) || "8".equals(fieldtypeoption)) {//分部
                        Map<String, Object> moderight_params_user = new HashMap<>();
                        moderight_params_user.put("dataLength", "1");
                        moderight_params_user.put("operation", "saveModeRight");
                        moderight_params_user.put("higherlevel_0", "1");
                        moderight_params_user.put("isRoleLimited_0", "0");
                        moderight_params_user.put("importtype_0", "1");
                        moderight_params_user.put("joblevel_0", "2");
                        moderight_params_user.put("layoutorder_0", "-1");
                        moderight_params_user.put("modefieldtype_0", "3");
                        moderight_params_user.put("browsersharetype_0", "1");
                        moderight_params_user.put("relatedid1000_0", newfieldid);
                        moderight_params_user.put("righttype_0", "1");
                        moderight_params_user.put("rolefieldtype_0", "1");
                        moderight_params_user.put("rolelevel_0", "0");
                        moderight_params_user.put("sharetype_0", "1000");
                        moderight_params_user.put("showlevel_0", "0");
                        moderight_params_user.put("modeid", modeId);
                        moderight_params_user.put("righttype", "3");
                        SaveModeRightList saveModeRightList_user = new SaveModeRightList(moderight_params_user, user);
                        saveModeRightList_user.execute(null);
                    }
                }
            }
        }


        //初始化布局
        ModeLayoutUtil modeLayoutUtil = new ModeLayoutUtil();
        Map<String, String> layout_params = new HashMap<>();
        layout_params.put("Id", "0");
        layout_params.put("formId", formid + "");
        layout_params.put("modeId", modeId);
        layout_params.put("type", "0");
        layout_params.put("name", modename + "-显示布局");
        layout_params.put("colsperrow", layoutRownum);
        layout_params.put("isdefault", "1");
        layout_params.put("needcreatenew", "0");
        layout_params.put("isExcel", "1");
        layout_params.put("layoutname", modename + "-显示布局");
        layout_params.put("excelStyle", layoutStyle);
        layout_params.put("excelIssys", "sys");
        layout_params.put("saveAttrFlag", "2");
        layout_params.put("operuser", user.getUID() + "");
        layout_params.put("opertime", DateHelper.getCurDateTime());

        //初始化布局字段
        rs.executeQuery("select * from workflow_billfield where billid=? order by dsporder", formid);
        while (rs.next()) {
            String fieldid = Util.null2String(rs.getString("id"));
            double dsporder = Util.getDoubleValue(rs.getString("dsporder"), 0.0);
            layout_params.put("mode" + fieldid + "_view_g0", "on");
            layout_params.put("mode" + fieldid + "_orderid_g0", dsporder + "");
        }

        int Id = modeLayoutUtil.batchHtmlField(layout_params);

        //rs.executeUpdate("update modehtmllayout set layoutname=? where id=? ",(modename+"-显示布局"),Id);

        //根据保存的信息， 需要拼2个json ：自定义属性json 和控件所需的json
        int excelStyle = Util.getIntValue(layoutStyle, 1);
        String issys = "sys";
        //1表示批量设置字段属性只保存，2表示批量设置字段属性并初始化，3表示模板列表页面初始化字段属性
        int saveAttrFlag = 2;
        ExcelsetInitManager excelsetInitManager = new ExcelsetInitManager();
        //excelsetInitManager.setRequest(request);
        excelsetInitManager.setUser(user);
        excelsetInitManager.setIsSys(issys);
        excelsetInitManager.setExcelStyle(excelStyle);
        int type = 0;
        int layoutid = excelsetInitManager.createSheetJson(Id, type, excelStyle);
        rs.executeUpdate("update modehtmllayout set layoutname=? where id=? ", (modename + "-显示布局"), Id);


        //创建查询列表
        Map<String, Object> list_params = new HashMap<>();
        list_params.put("customname", searchName);
        list_params.put("formid", formid);
        list_params.put("modeid", modeId);
        list_params.put("modetype", appid);
        list_params.put("appid", appid);
        list_params.put("opentype", "0");
        list_params.put("pagenumber", "10");
        ListInfoSave listInfoSave = new ListInfoSave(list_params, user);
        Map<String, Object> customResult = listInfoSave.execute(null);
        String customid = Util.null2String(customResult.get("customid"));

        Map<String, Object> listright_params = new HashMap<>();
        listright_params.put("customid", customid);
        JSONArray listrightData = new JSONArray();
        JSONObject listrightJson = new JSONObject();
        listrightJson.put("relatedid4", 2);
        listrightJson.put("rolelevel", 0);
        listrightJson.put("sharetype", 4);
        listrightJson.put("rolefieldtype", 1);
        String[] showlevelArray = {"0", ""};
        listrightJson.put("showlevel", showlevelArray);
        listrightJson.put("joblevel", 2);
        listrightJson.put("sharetypespan", "角色");
        listrightJson.put("relatedidspan", "系统管理员");
        listrightJson.put("rolelevelspan", "系统管理员");
        listrightJson.put("relatedidspan", "部门");
        listrightJson.put("showlevelspan", "0");
        listrightData.add(listrightJson);
        listright_params.put("data", listrightData.toJSONString());
        listright_params.put("righttype", "1");
        SaveRightinfoCmd saveRightinfoCmd = new SaveRightinfoCmd(listright_params, user);
        saveRightinfoCmd.execute(null);


        listright_params = new HashMap<>();
        listright_params.put("customid", customid);
        listrightData = new JSONArray();
        listrightJson = new JSONObject();
        listrightJson.put("rolelevel", 0);
        listrightJson.put("sharetype", 5);
        listrightJson.put("rolefieldtype", 1);
        String[] showlevelArray_all = {"0", ""};
        listrightJson.put("showlevel", showlevelArray_all);
        listrightJson.put("joblevel", 2);
        listrightJson.put("sharetypespan", "所有人");
        listrightJson.put("showlevelspan", "0");
        listrightData.add(listrightJson);
        listright_params.put("data", listrightData.toJSONString());
        listright_params.put("righttype", "1");
        saveRightinfoCmd = new SaveRightinfoCmd(listright_params, user);
        saveRightinfoCmd.execute(null);

        List<Map<String, Object>> jsonArray = new ArrayList<Map<String, Object>>();

        String sql = "select b.id,b.fieldname,h.labelname,b.fieldhtmltype,b.type,b.dsporder,b.fieldlabel,b.viewtype from workflow_billfield b,HtmlLabelInfo h  where b.fieldlabel=h.indexid and h.languageid=7 " +
                " and  billid=? order by dsporder";
        rs.executeQuery(sql, formid);
        while (rs.next()) {
            Map<String, Object> jsonObject = new HashMap<>();
            String fieldid = Util.null2String(rs.getString("id"));
            if (showFeilds.contains(fieldid)) {
                jsonObject.put("isshow", "1");
            } else {
                jsonObject.put("isshow", "0");
            }

            String hreflink = "";
            String istitle = "0";
            if (linkFeilds.contains(fieldid)) {
                hreflink = "/spa/cube/index.html#/main/cube/card?type=$type$&modeId=$modeId$&formId=$formId$&billid=$billid$&opentype=$opentype$&customid=$customid$&viewfrom=$viewfrom$";
                istitle = "1";
            }
            if (showorderFeilds.contains(fieldid)) {
                jsonObject.put("showorder", Util.getDoubleValue(showorderFeildsMap.get(fieldid), 0));
            } else {
                jsonObject.put("showorder", 0);
            }
            if (queryFeilds.contains(fieldid)) {
                jsonObject.put("isquery", "1");
            } else {
                jsonObject.put("isquery", "0");
            }

            String fieldname = Util.null2String(rs.getString("fieldname"));
            String labelname = Util.null2String(rs.getString("labelname"));
            String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype"));
            String fieldtype = Util.null2String(rs.getString("type"));
            String fieldlabel = Util.null2String(rs.getString("fieldlabel"));
            String viewtype = Util.null2String(rs.getString("viewtype"));
            double dsporder = Util.getDoubleValue(rs.getString("dsporder"), 0.0);


            jsonObject.put("fieldname", fieldname);
            jsonObject.put("fieldlabelname", labelname);

            jsonObject.put("isgroup", "0");
            jsonObject.put("istitle", istitle);
            jsonObject.put("hreflink", hreflink);

            jsonObject.put("randomkey", fieldid);
            jsonObject.put("fieldlabel", fieldlabel);
            jsonObject.put("randomFieldId", fieldid);
            jsonObject.put("fieldid", fieldid);

            jsonObject.put("fieldhtmltype", fieldhtmltype);
            jsonObject.put("fieldtype", fieldtype);
            jsonObject.put("viewtype", viewtype);

            jsonObject.put("qfws", "");
            jsonObject.put("_modified_", "true");
            jsonObject.put("requiredCon", "0");
            jsonObject.put("iskey", "0");
            jsonObject.put("isstat", "0");
            jsonObject.put("selectoptions", "[]");
            jsonObject.put("isencrypt", "0");
            jsonObject.put("advancedqueryorder", "0");
            jsonObject.put("ismaplocation", "0");
            jsonObject.put("isorder", "0");
            jsonObject.put("requiredConSpan", "");
            jsonObject.put("queryorder", "0");
            jsonObject.put("conditionTransition", "0");
            jsonObject.put("showmethod", "0");
            jsonObject.put("editable", "0");
            jsonObject.put("canorder", "true");
            jsonObject.put("ordernum", "0");
            jsonObject.put("groupset", "0");
            jsonObject.put("isadvancedquery", "0");
            jsonObject.put("addable", "0");
            jsonObject.put("colwidth", "0.00");
            jsonObject.put("conditionValue", "");
            jsonObject.put("isDealBrowser", "1");
            jsonObject.put("searchpara", "");
            jsonObject.put("alignment", "1");
            jsonObject.put("ordertype", "0");

            jsonArray.add(jsonObject);
        }
        Map<String, Object> formfields_params = new HashMap<>();
        formfields_params.put("data", JSON.toJSONString(jsonArray));
        formfields_params.put("customid", customid);
        new BaseBean().writeLog("JSONArray.toJSONString(jsonArray):" + JSON.toJSONString(jsonArray));
        try {
            new BaseBean().writeLog("new String(JSONArray.toJSONString(jsonArray).getBytes(), \"UTF-8\"):" + new String(JSON.toJSONString(jsonArray).getBytes(), "UTF-8"));
            formfields_params.put("data", JSON.toJSONString(jsonArray));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        SaveFormfieldsCmd saveFormfieldsCmd = new SaveFormfieldsCmd(formfields_params, user);
        saveFormfieldsCmd.execute(null);
        //更新linke 字段
        for (int m = 0; m < linkFeilds.size(); m++) {
            String linkFeildid = linkFeilds.get(m);
            String hreflink = "/spa/cube/index.html#/main/cube/card?type=$type$&modeId=$modeId$&formId=$formId$&billid=$billid$&opentype=$opentype$&customid=$customid$&viewfrom=$viewfrom$";
            rs.executeUpdate("update mode_CustomDspField set hreflink =? where fieldid=? and customid=?", hreflink, linkFeildid, customid);
        }
        Map<String, Object> sqsi_params = new HashMap<>();
        sqsi_params.put("id", 0);
        sqsi_params.put("customid", customid);
        JSONArray dataArray = new JSONArray();
        sql = "select b.id,b.fieldname,h.labelname,b.fieldhtmltype,b.type,b.dsporder,b.fieldlabel,b.viewtype from workflow_billfield b,HtmlLabelInfo h  where b.fieldlabel=h.indexid and h.languageid=7 " +
                " and  billid=? order by dsporder";
        rs.executeQuery(sql, formid);
        while (rs.next()) {
            JSONObject jsonObject = new JSONObject();
            String fieldid = Util.null2String(rs.getString("id"));
            String fieldname = Util.null2String(rs.getString("fieldname"));
            String labelname = Util.null2String(rs.getString("labelname"));
            String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype"));
            String fieldtype = Util.null2String(rs.getString("type"));
            String fieldlabel = Util.null2String(rs.getString("fieldlabel"));
            String viewtype = Util.null2String(rs.getString("viewtype"));
            double dsporder = Util.getDoubleValue(rs.getString("dsporder"), 0.0);
            if (!queryFeilds.contains(fieldid)) {
                continue;
            }
            jsonObject.put("key", UUID.randomUUID().toString());
            jsonObject.put("customname", labelname);
            jsonObject.put("range", "字段本身值");
            jsonObject.put("condition", "");
            jsonObject.put("orderid", dsporder);
            jsonObject.put("type", fieldtype);
            jsonObject.put("isdetailtable", 0);
            jsonObject.put("fieldid", fieldid);
            dataArray.add(jsonObject);
        }
        sqsi_params.put("data", JSONArray.toJSONString(dataArray));
        sqsi_params.put("isquicksearch", 1);
        sqsi_params.put("isshowtype", 0);
        sqsi_params.put("ishidename", 0);
        SaveQuickSearchInfoCmd saveQuickSearchInfoCmd = new SaveQuickSearchInfoCmd(sqsi_params, user);
        Map<String, Object> sqsi_resultMap = saveQuickSearchInfoCmd.execute(null);
        sqsi_params.putAll(sqsi_resultMap);
        sqsi_params.put("modeid", modeId);
        sqsi_params.put("customid", customid);

        Map<String, Object> resultInfo = new HashMap<>();
        resultInfo.put("modeid", modeId);
        resultInfo.put("modename", modename);
        resultInfo.put("formid", formid);
        resultInfo.put("formname", formname);
        resultInfo.put("searchid", customid);
        resultInfo.put("searchname", searchName);
        resultInfo.put("modeurl", "/spa/cube/index.html#/main/cube/card?type=1&modeId=" + modeId + "&formId=" + formid);
        resultInfo.put("searchurl", "/spa/cube/index.html#/main/cube/search?customid=" + customid);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("resultInfo", resultInfo);

        rs.executeUpdate("insert into CubeQuickCreateLog(viewname,modeid)values(?,?)", viewtablename, modeId);
        return resultMap;
    }


    public String getNewVirFormName(String formname) {
        RecordSet rs = new RecordSet();
        String sql = "select b.labelname from workflow_bill a, HtmlLabelInfo b " +
                " where b.indexid=a.namelabel and b.languageid=" + user.getLanguage() + " and b.labelname like '%" + formname + "_cp%' ";
        rs.executeQuery(sql);
        if (rs.getCounts() > 0) {
            int maxindex = 0;
            while (rs.next()) {//新表单名和单据名
                String labelname = Util.null2String(rs.getString("labelname"));
                String index = labelname.replaceAll(formname + "_cp", "");
                int inIndex = Util.getIntValue(index, 0);
                if (inIndex > maxindex) {
                    maxindex = inIndex;
                }
            }
            formname = formname + "_cp" + (maxindex + 1);
        } else {
            formname = formname + "_cp1";
        }
        return formname;
    }


    private static JSONArray sortProxyAndCdn(JSONArray bindArrayResult) {
        List<JSONObject> list = JSONArray.parseArray(bindArrayResult.toJSONString(), JSONObject.class);
        System.out.println("排序前：" + bindArrayResult);
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                double a = Util.getDoubleValue(o1.getString("showorder"), 0);
                double b = Util.getDoubleValue(o2.getString("showorder"), 0);
                if (a > b) {
                    return -1;
                } else if (a == b) {
                    return 0;
                } else
                    return 1;
            }
        });
        JSONArray jsonArray = JSONArray.parseArray(list.toString());
        System.out.println("排序后：" + jsonArray);
        return jsonArray;
    }


    private static String getAppid() {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from modeTreeField where treeFieldName = ? and (isdelete=0 or isdelete is null)", "历史数据迁移");
        rs.next();
        return Util.null2String(rs.getString("id"));
    }
}
